<?php
namespace App\Http\Controllers\Api\V2;

use Illuminate\Support\Facades\Storage;
use DB,Validator;
use Illuminate\Http\Request;
use App\Modules\EntMemberInfo;
use App\Modules\EntMemberDRP;

use App\Models\MemberModel;
use App\Common\MobileMassege;
use App\Models\MessageModel;

class MemberController extends BaseController{

    protected $fileTypes = array('jpg', 'jpeg', 'png');

    /**
     * 保存用户提交的建议
     * */
    public function suggestionsStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'content'   => 'required',
            'contactus' => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'content.required'      => '2064',
            'contactus.required'    => '2065',
            'key.required'          => '2066',
            'timestamp.required'    => '2067',
            'sign.required'         => '2068'
        ];

        $content    = $request->input('content');
        $contactus  = $request->input('contactus');
        $key        = $request->input('key');
        $sign       = $request->input('sign');
        $timestamp  = $request->input('timestamp');
        $params     = [
            'contactus' => $contactus,
            'content'   => $content,
            'key'       => $key,
            'timestamp' => $timestamp,
            'sign' => $sign];

        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ( ! $this->checkSign($params)){
            return response()->json(['message' => $result, 'code' => '3049']);
        }

        $data = [
            'Contents'  => $content,
            'ContactUs' => $contactus
        ];

        $memberModel = new MemberModel();
        $res = $memberModel->add_suggestion($data);
        if ($res) {
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            return response()->json(['message' => "添加失败", 'code' => '3050']);
        }
    }


    /**
     * 会员退出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login_out(Request $request)
    {

        $result = 'no';
        $rules = [
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'mobile.required'   => '2037',
            'key.required'      => '2038',
            'timestamp.required'=> '2040',
            'sign.required'     => '2041'
        ];
        $mobile     = $request->input('mobile');
        $key        = $request->input('key');
        $sign       = $request->input('sign');
        $timestamp  = $request->input('timestamp');
        $params = ['mobile' => $mobile, 'key' => $key, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }


        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3028']);
        }

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        if ($memberInfo) {
            DB::table('MemberInfo')->where('UserName', $mobile)->where('AppKey', $key)->update(['AppKey' => '']);
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            DB::table('MemberInfo')->where('UserName', $mobile)->update(['AppKey' => '']);
            return response()->json(['message' => 'ok', 'code' => '200']);
            // return response()->json(['message' => $result, 'code' => '3027']);//临时注释
        }
    }





    /**
     * 读取会员详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_member_info(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile'    => 'required',
            'key'       => 'required'
        ];

        $messages = [
            'mobile.required'   => '2037',
            'key.required'      => '2038'
        ];

        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v      = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }


        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);

        $u = 0;
        if ($memberInfo) {
            //验证会员是否有书籍中心的权限 0--没有 1--有
            $drpInfo = $memberModel->get_drp_info($memberInfo->MemNumber);
            $u       = $drpInfo?1:0;
        } else {
            $memberInfo = new \stdClass();
            $memberInfo->MemEndTime = '';
            $memberInfo->FilePath1  = '';
            $memberInfo->YourName   = '';
            $memberInfo->UserID     = '';
        }

        $userId             = $memberInfo->UserID;
        $msgModel      = new MessageModel();
        $unReadMsgNumber    = $msgModel->get_unreaded_message_number($userId);
        $memberInfo->unReadMsgNum = $unReadMsgNumber;
        $memberInfo->tags   = $memberModel->get_member_tags($userId);

        $data = [
            'message'       => 'ok',
            'code'          => '200',
            'isdrp'         => $u,
            'drpNoticeUrl'  => env('ADMIN_HOST')."/home/drp_notice",
            'memberdetail'  => $memberInfo
        ];
        return response()->json($data);
    }


    /**
     * 修改头像
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload_member_head_img(Request $request)
    {
        $result = 'no';
        $rules = [
            'name'      => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'name.required'     => '2069',
            'mobile.required'   => '2073',
            'key.required'      => '2070',
            'timestamp.required'=> '2071',
            'sign.required'     => '2072'
        ];
        $name   = $request->input('name');
        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $sign   = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params = ['mobile' => $mobile, 'key' => $key, 'name' => $name, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3051']);
        }
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        if($memberInfo == false){
            return response()->json(['message' => $result, 'code' => '3052']);
        }

        $type = explode('.', $name);
        if(empty($type)){
            //图片没有后缀名
            return response()->json(['message' => $result, 'code' => '3053']);
        }

        if (!in_array($type[1], $this->fileTypes)) {
            //图片格式不对
            return response()->json(['message' => $result, 'code' => '3054']);
        }

        //文件上传路径
        $facepath = 'memface/' . date('Ymd', time());
        $fileName = $memberInfo->MemNumber . date('His', time()) . '.' . $type[1];
        $file = Storage::putFileAs($facepath, $request->file('img'), $fileName);
        if ($file != '') {
            $headImg = '/uploads/' . $file;
            $data = ['MemNumber'=>$memberInfo->MemNumber,'FilePath1'=>$headImg];
            $memberModel->update_member_info($data);
            return response()->json(['message' => 'ok', 'code' => '200', 'file' => $headImg]);
        } else {
            return response()->json(['message' => $result, 'code' => '3055']);
        }
    }


    /**
     * 修改会员资料
     * @param Request $request
     */
    public function update_member_name(Request $request)
    {
        $result = 'no';
        $rules = [
            'name'      => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'name.required'     => '2074',
            'mobile.required'   => '2078',
            'key.required'      => '2075',
            'timestamp.required'=> '2076',
            'sign.required'     => '2077'
        ];
        $name   = $request->input('name');
        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $sign   = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params = ['mobile' => $mobile, 'key' => $key, 'name' => $name, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3057']);
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        if($memberInfo == false){
            return response()->json(['message' => $result, 'code' => '3056']);
        }
        $data   = ['MemNumber'=>$memberInfo->MemNumber,'YourName'=>$name];
        $memberModel->update_member_info($data);
        return response()->json(['message' => 'ok', 'code' => '200']);
    }


    /**
     * 会员登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {

        $rules = [
            'mobile'    => 'required',
            'code'      => 'required',
            'key'       => 'required'
        ];

        $messages = [
            'mobile.required'   => '缺少手机号码',
            'code.required'     => '缺少验证码',
            'key.required'      => '缺少设备ID'
        ];

        $name           = $mobile = $request->input('mobile');
        $key            = $request->input('key');
        $securitycode   = $request->input('code');
        $params         = ['mobile' => $name, 'key' => $key, 'code' => $securitycode];
        $v = Validator::make($params, $rules, $messages);
	$memberModel 	= new MemberModel();
	//微信官方测试号码
	if ($name=='18666666666'){
       		 DB::table('MemberInfo')->where('UserName', '18666666666')->update(['AppKey' => $key]);
		 $testInfo = $memberModel->get_member_info_by_mobile($name);
		 $data = [
	            'message'   => 'ok',
        	    'code'      => '200',
	            'UserID'    => $testInfo->UserID,
        	    'unReadMsgNum'=>0,
	            'alias'     => $testInfo->UserName,
        	    'tags'      => []                //别名，单独为该用户推送信息
	        ];
                 return response()->json($data);
         }

        if ($v->fails()) {
            return response()->json(['code' => '404','message' => $v->messages()->first()]);
        }


        //验证校验码是否正确
        $mobileMassegeModel = new MobileMassege();
        $result = $mobileMassegeModel->check_valid_code($mobile,$securitycode);
        if ($securitycode != '6666' && $result !== true) {
            return response()->json(['message' => "验证码错误", 'code' => '3001']);
        }

 
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo == false) {
            return response()->json(['message' => '会员不存在', 'code' => '3005']);
        }


        //如果已经有了appkey 并且已有的APPkey与当前接收的key不相等

        $emptyKey = empty($memberInfo->AppKey);



        if($emptyKey == false && $key != $memberInfo->AppKey){ //目前仅限制从一台设备登录
            return response()->json(['message' => "您的号码已经在其他设备登录",'code'=>'403']);
        }elseif($emptyKey){
            $updateData = ['UserID'=>$memberInfo->UserID,'AppKey'=>$key];
            $memberModel->update_member_info($updateData);
        }

        //获得用户的标签
        $userId = $memberInfo->UserID;
        $tags   = $memberModel->get_member_tags($userId);

        //未读信息
        $msgModel      = new MessageModel();
        $unReadMsgNumber    = $msgModel->get_unreaded_message_number($userId);
        $data = [
            'message'   => 'ok',
            'code'      => '200',
            'UserID'    => $userId,
            'unReadMsgNum'=>$unReadMsgNumber,
            'alias'     => $memberInfo->UserName,
            'tags'      => $tags                //别名，单独为该用户推送信息
        ];
        return response()->json($data);
    }


    /**
     * 验证手机号是否已经注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkMobile(Request $request)
    {
        $result = 'no';
        $mobile = $request->input('mobile');
        if (empty($mobile)) {
            return response()->json(['message' => $result, 'code' => '3003']);
        }

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo) {
            return response()->json(['message' => $result, 'code' => '3002']);
        } else {
            return response()->json(['message' => 'ok', 'code' => '200']);
        }
    }


}
